package ia.util;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import lejos.pc.comm.NXTCommLogListener;

@SuppressWarnings("all")

/**
 * Crea loggers que pueden agregarse a clases que extiendan NXTCommLoggable
 * 
 * @author Armando Andini
 *
 */
public class Logger{
	private static class ConsoleLogger implements NXTCommLogListener {

		@Override
		public void logEvent(String arg0) {
			System.out.println("DEBUG: "+arg0);
			
		}

		@Override
		public void logEvent(Throwable arg0) {
			arg0.printStackTrace(System.out);
			
		}
		
	}
	
	private static class FileLogger implements NXTCommLogListener {
		public FileLogger(){
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			try{
				PrintWriter out = this.openFile();
				out.println("\n\n----- LOG "+dateFormat.format(date)+" -----");
				out.close();
			}
			catch (IOException e){
				System.out.println("No se puede loggear en el archivo");
			}
		}
		
		@Override
		public void logEvent(String arg0) {
			try {
				PrintWriter out = this.openFile();
				out.println("DEBUG: "+arg0);
				out.close();
			} catch (IOException e) {
				System.out.println("No se puede loggear en el archivo");
			}
			
		}

		@Override
		public void logEvent(Throwable arg0) {
			try{
				PrintWriter out = this.openFile();
				arg0.printStackTrace(out);
				out.close();
			}
			catch (IOException e){
				System.out.println("No se puede loggear en el archivo");
			}
			
		}
		
		protected PrintWriter openFile() throws IOException{
			PrintWriter out = new PrintWriter(new FileWriter("Log/Log.txt",true));
			return out;
		}
		
	}
	
	public static int CONSOLE = 0;
	public static int FILE = 1;
	
	
	public static NXTCommLogListener getLogger(){
		return getLogger(CONSOLE);
	}
	public static NXTCommLogListener getLogger(int type){
		if(type == CONSOLE){
			return new ConsoleLogger();
		}
		else if(type == FILE){
			return new FileLogger();
		}
		return null;
	}
	
	
}